package com.bxl.netty.rpc.client.common.pool;

import com.bxl.netty.rpc.client.common.client.AppInfo;
import com.bxl.netty.rpc.client.common.client.ClientInfo;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;

/**
 * <>
 *
 * @author baixl
 * @date 2021/2/24
 */
public class ZoneClientPool {
    private ConcurrentHashMap<String, AppInfo> zones = new ConcurrentHashMap<String, AppInfo>();
    
    private boolean isInit = false;
    private CountDownLatch count = new CountDownLatch(1);
    
    public ClientInfo getClientInfo(String zoneId) {
        return zones.get(zoneId).getClient();
    }

    public void addZone(AppInfo zoneInfo){
        zones.putIfAbsent(zoneInfo.getApp(),zoneInfo); 
    }

    public void updateZone(AppInfo zoneInfo){
        zones.put(zoneInfo.getApp(),zoneInfo);
    }
    
    public void init(){
        isInit=true;
        count.countDown();
    }


    public NioSocketChannel getClient(String zoneId) {
        try {
            return zones.get(zoneId).getClient().getClient();
        } catch (Exception e) {
            e.printStackTrace();
            try {
                return zones.get(zoneId).getClient().getClient();
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
        return null;
    }
    
    public NioSocketChannel getClientWaitInit(String zoneId) {
        try {
            if(!isInit){
                count.await();
            }
            return zones.get(zoneId).getClient().getClient();
        } catch (Exception e) {
            e.printStackTrace();
            try {
                return zones.get(zoneId).getClient().getClient();
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
        return null;
    }
    
    
    
    

    public List<ClientInfo> getClients(String zoneId) {
        try {
            return zones.get(zoneId).getClients();
        } catch (Exception e) {
        }
        return null;
    }
    
    public void setClients(String zoneId,List<ClientInfo> clientInfos){
        zones.get(zoneId).setClients(clientInfos);
    }
}
